package com.hup.minicontroller.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 * @author hugan
 * @date 2021/5/23
 */
@Slf4j
public abstract class NetUtil {

    /**
     * 获取局域网的网关地址
     *
     * @return defValue-解析异常时的返回值
     * @apiNote 只是简单的把获取到的ipv4.ip的第四位改成1而已, 很多情况下是不准确的(路由器改了网关, 安卓热点等)
     */
    public static String getGatewayIp(String defValue) {
        try {
            String address = InetAddress.getLocalHost().getHostAddress();
            if (StringUtils.isBlank(address)) return defValue;
            if ("127.0.0.1".equals(address)) return address;
            String[] split = address.split("\\.");
            if (split.length != 4) return defValue;
            return split[0] + "." + split[1] + "." + split[2] + ".1";
        } catch (UnknownHostException e) {
            return defValue;
        }
    }

    /**
     * 获取本机ip;支持多网卡
     *
     * @return defValue-解析异常时的返回值
     */
    public static List<String> getGatewayIps(String defValue) {
        try {
            ArrayList<String> res = new ArrayList<>();

            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual())
                    continue; // 跳过未启用、回环和虚拟接口

                //log.info("displayName={}, name={}", networkInterface.getDisplayName(), networkInterface.getName());
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (!(inetAddress instanceof Inet4Address)) continue;

                    //log.info("ip={}", inetAddress.getHostAddress());
                    res.add(inetAddress.getHostAddress());
                }
            }
            return res;
        } catch (Exception e) {
            return Collections.singletonList(defValue);
        }
    }

}
